package com.lry.rpc.netty;

import com.lry.common.CommonConstants;
import com.lry.exception.FrameworkException;
import com.lry.protocol.RpcInvocation;
import com.lry.util.CollectionUtils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Objects;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class BeanKey {
    private String interfaceName;
    private String implName;
    private String version;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        BeanKey that = (BeanKey) o;
        return Objects.equals(interfaceName, that.interfaceName) &&
                Objects.equals(implName, that.implName) &&
                Objects.equals(version, that.version);
    }

    @Override
    public int hashCode() {
        return Objects.hash(interfaceName, implName, version);
    }

    public static BeanKey getBeanKey(RpcInvocation rpcInvocation){
        if(null==rpcInvocation){
            throw new FrameworkException("rpcInvocation is null");
        }
        String implName = "";
        String version = "";
        if(CollectionUtils.isNotEmpty(rpcInvocation.getAttachments())){
            implName = (String) rpcInvocation.getAttachments().get(CommonConstants.SPEC_IMPL_NAME_KEY);
            if(null==implName){
                implName="";
            }
            version = (String) rpcInvocation.getAttachments().get(CommonConstants.SPEC_VERSION_KEY);
            if(null==version){
                version="";
            }
        }
        BeanKey beanKey = new BeanKey(rpcInvocation.getTargetServiceName(),implName,version);
        return beanKey;
    }
}
